package com.iotechn.uninotify.service.open;

import com.alibaba.fastjson.JSONObject;
import com.iotechn.uninotify.domain.DeveloperUserDO;
import com.iotechn.uninotify.exception.NotifyExceptionDefinition;
import com.iotechn.uninotify.exception.NotifyServiceException;
import com.iotechn.uninotify.exception.ServiceException;
import com.iotechn.uninotify.service.biz.DeveloperBizService;
import com.iotechn.uninotify.service.biz.WxMpBizService;
import com.iotechn.uninotify.util.RequestUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/12/26
 * Time: 23:34
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private WxMpBizService wxMpBizService;

    @Autowired
    private DeveloperBizService developerBizService;

    @Value("${com.iotechn.neworder.template-id}")
    private String newOrderTemplateId;

    @Value("${com.iotechn.refundorder.template-id}")
    private String refundOrderTemplateId;

    @Value("${com.iotechn.uninotify.name}")
    private String name;

    private OkHttpClient okHttpClient = new OkHttpClient();

    @Override
    public List getValidTemplates() throws ServiceException {
        try {
            String accessToken = wxMpBizService.getAccessToken();
            String json = okHttpClient.newCall(
                    new Request.Builder()
                            .get()
                            .url("https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" + accessToken).build())
                    .execute().body().string();
            JSONObject jsonObject = JSONObject.parseObject(json);
            return jsonObject.getJSONArray("template_list");
        } catch (IOException e) {
            throw new NotifyServiceException(NotifyExceptionDefinition.NOTIFY_IO_EXCEPTION);
        }
    }

    @Override
    public String customNotify(String userId, String templateId, String data) throws ServiceException {
        DeveloperUserDO developerUserDO = developerBizService.getUserById(RequestUtil.getDeveloper().getAppId(), userId);
        try {
            String accessToken = wxMpBizService.getAccessToken();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, this.buildBaseTemplate(developerUserDO, templateId, JSONObject.parseObject(data)).toJSONString());
            String json = okHttpClient.newCall(
                    new Request.Builder()
                            .post(body)
                            .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken).build())
                    .execute().body().string();
            JSONObject jsonObject = JSONObject.parseObject(json);
            Integer errcode = jsonObject.getInteger("errcode");
            if (errcode == null || errcode == 0) {
                return "ok";
            }
            throw new NotifyServiceException(jsonObject.getString("errmsg"), NotifyExceptionDefinition.NOTIFY_THIRD_PART_EXCEPTION.getCode());
        } catch (IOException e) {
            throw new NotifyServiceException(NotifyExceptionDefinition.NOTIFY_IO_EXCEPTION);
        }
    }

    @Override
    public String newOrderNotify(String userId, String orderNo, String actualPrice, String payChannel, String consignee, String phone, String address, String skuInfo) throws ServiceException {
        JSONObject data = new JSONObject();
        data.put("first", this.buildParamObj("有新订单，请及时发货", "#0"));
        data.put("remark", this.buildParamObj("感谢您使用" + this.name + "通知中心", "#0"));
        data.put("keyword1", this.buildParamObj(orderNo, "#FF"));
        data.put("keyword2", this.buildParamObj(skuInfo, "#0"));
        data.put("keyword3", this.buildParamObj(actualPrice, "#0"));
        data.put("keyword4", this.buildParamObj(payChannel, "#0"));
        data.put("keyword5", this.buildParamObj(consignee + "," + phone + "," + address, "#0"));
        return this.customNotify(userId, this.newOrderTemplateId, data.toJSONString());
    }

    @Override
    public String refundOrderNotify(String userId, String refundPrice, String skuInfo, String orderNo) throws ServiceException {
        JSONObject data = new JSONObject();
        data.put("first", this.buildParamObj("订单有退款申请，请及时处理", "#0"));
        data.put("remark", this.buildParamObj("感谢您使用" + this.name + "通知中心", "#0"));
        data.put("orderProductPrice", this.buildParamObj( refundPrice, "#0"));
        data.put("orderProductName", this.buildParamObj(skuInfo, "#0"));
        data.put("orderName", this.buildParamObj( orderNo, "#FF"));
        return this.customNotify(userId, this.refundOrderTemplateId, data.toJSONString());
    }

    private JSONObject buildBaseTemplate(DeveloperUserDO developerUserDO, String templateId, JSONObject data) {
        JSONObject paramObj = new JSONObject();
        paramObj.put("touser", developerUserDO.getOpenId());
        paramObj.put("template_id", templateId);
        paramObj.put("data", data);
        return paramObj;
    }

    private JSONObject buildParamObj(String value, String color) {
        JSONObject item = new JSONObject();
        item.put("value", value);
        item.put("color", color);
        return item;
    }

}
